package org.box.metadata.shell.web.ws.cs;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.box.metadata.shell.web.WebShell;
import org.box.metadata.shell.web.server.ServerCallback;

import com.sun.jersey.spi.resource.Singleton;

@Path("server")
@Singleton
public class ServerController {
	
	private final static Logger LOG = Logger.getLogger(ServerController.class.getName());
	
	@Path("/log")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public ServerCallback getLog(
			@Context ServletContext context,
			@Context HttpServletRequest req, 
			@QueryParam("li") int li) {

    	if (LOG.isLoggable(Level.FINE)) 
    		LOG.fine("RequestedSessionIdValid: " + req.isRequestedSessionIdValid());
	
    	WebShell shell = getShell(context);
		HttpSession session = req.getSession(true);
		String sid = session != null ? session.getId() : null;
		
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("Session: " + sid + "; LI: " + li + "; currentInput: " + shell.getCurrentInput());		

		return new ServerCallback(shell.getOutStream(), li, sid, shell.getCurrentInput() != null);
		
	}

	@Path("/command")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public ServerCallback submitCommand(
			@Context ServletContext context,
			@Context HttpServletRequest req,
			@FormParam("li") int li,
			@FormParam("cmd") String cmd) {

		WebShell shell = getShell(context);
	
    	if (LOG.isLoggable(Level.FINE)) 
    		LOG.fine("RequestedSessionIdValid: " + req.isRequestedSessionIdValid());
    	
		HttpSession session = req.getSession(true);
		String sid = session.getId();
		
		if (LOG.isLoggable(Level.FINE)) 
		    LOG.fine("Session: " + sid + "; cmd: " + cmd);		

		if (cmd != null && !cmd.trim().isEmpty())
			getShell(context).submitInput(cmd, sid);
		
		return new ServerCallback(shell.getOutStream(), li, sid, true);
	}

	protected WebShell getShell(ServletContext context) {
		return (WebShell) context.getAttribute(WebShell.SERVLET_CONTEXT_SHELL_ATTRIBUTE);
	}

}
